package com.test.jdk9.trywithres;

import java.io.*;

/**
 * @Description: TODO
 * @Author 赵侠客
 * @Date 2023/6/3
 **/
public class TryWithRes {

    public static void main(String[] args) throws IOException {
        //JDK8之前
        InputStream inputStream = null;
        try {
            inputStream = TryWithRes.class.getClassLoader().getResourceAsStream("test.txt");
            System.out.println(new String(inputStream.readAllBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }


        //JDK8 try-with-resource
        try (InputStream inputStream8 =  TryWithRes.class.getClassLoader().getResourceAsStream("test.txt")) {
            System.out.println(new String(inputStream8.readAllBytes()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        //JDK9 新的try-with-resouce
        InputStream inputStream9_1 =  TryWithRes.class.getClassLoader().getResourceAsStream("test.txt");
        InputStream inputStream9_2 =  TryWithRes.class.getClassLoader().getResourceAsStream("test2.txt");
        try(inputStream9_1;inputStream9_2) {
            System.out.println(new String(inputStream9_1.readAllBytes()));
            System.out.println(new String(inputStream9_2.readAllBytes()));
            System.out.println("inputStream9_1 是否关闭："+inputStream9_1.available());
        }catch (Exception e){
            e.printStackTrace();
        }


    }


}
